import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yi_shop/components/home/home.dart';
import 'package:yi_shop/event/index.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';

class HomeController extends GetxController {
  RxInt index = 0.obs;

  late PageController pageController;

  late StreamSubscription<HomeChangeIndexEvent> stream;

  @override
  void onInit() {
    pageController = PageController(initialPage: index.value);
    stream = eventBus.on<HomeChangeIndexEvent>().listen((HomeChangeIndexEvent event) {
      index.value = event.index;
      gotoView();
    });
    super.onInit();
  }

  @override
  void onClose() {
    stream.cancel();
    pageController.dispose();
    super.onClose();
  }

  void gotoView() {
    pageController.animateToPage(index.value,
        duration: const Duration(milliseconds: 500), curve: Curves.linear);
  }
}

class HomePage extends GetView<HomeController> {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorD7d7),
      body: createdBodyView(context),
      bottomNavigationBar: Obx(() => BottomNavigationBar(
            currentIndex: controller.index.value,
            type: BottomNavigationBarType.fixed,
            elevation: 1,
            backgroundColor: Colors.white,
            iconSize: 20.w,
            selectedFontSize: 12.sp,
            selectedItemColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048),
            unselectedFontSize: 12.sp,
            unselectedItemColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorCccc),
            landscapeLayout: BottomNavigationBarLandscapeLayout.centered,
            items: <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                icon: assetName('u3388'),
                activeIcon: assetName('u386'),
                label: '首页',
              ),
              BottomNavigationBarItem(
                icon: assetName('u387'),
                activeIcon: assetName('u3389'),
                label: '分类',
              ),
              BottomNavigationBarItem(
                icon: assetName(
                  'u390',
                ),
                activeIcon: assetName('u10808'),
                label: '社区',
              ),
              BottomNavigationBarItem(
                icon: assetName('u389'),
                activeIcon: assetName('u12207'),
                label: '消息',
              ),
              BottomNavigationBarItem(
                icon: assetName(
                  'u388',
                ),
                activeIcon: assetName('u14149'),
                label: '我的',
              ),
            ],
            selectedLabelStyle:
                StylesUtils.customTextStyle(fontSize: 12.sp, color: ColorsUtils.colorF048),
            unselectedLabelStyle:
                StylesUtils.customTextStyle(fontSize: 12.sp, color: ColorsUtils.colorCccc),
            onTap: (int i) {
              if (i != controller.index.value) {
                controller.index.value = i;
                controller.gotoView();
              }
            },
          )),
    );
  }

  Widget assetName(String name) {
    return SvgUtils.assetName(name, width: 20.w, height: 20.h);
  }

  PageView createdBodyView(BuildContext context) {
    return PageView(
      physics: const NeverScrollableScrollPhysics(),
      scrollBehavior: const ScrollBehavior(),
      controller: controller.pageController,
      children: [
        _KeepAliveWrapper(
          child: const HomeIndexView(),
          callback: () {
            Get.lazyPut(() => HomeIndexController());
          },
        ),
        _KeepAliveWrapper(
          child: const HomeClassifyView(),
          callback: () {
            Get.lazyPut(() => HomeClassifyController());
          },
        ),
        _KeepAliveWrapper(
            child: const HomeCommunityView(),
            callback: () {
              Get.lazyPut(() => HomeCommunityController());
            }),
        _KeepAliveWrapper(
            child: const HomeMessageView(),
            callback: () {
              Get.lazyPut(() => HomeMessageController());
            }),
        _KeepAliveWrapper(
            child: const HomeMineView(),
            callback: () {
              Get.lazyPut(() => HomeMineController());
            }),
      ],
    );
  }
}

class _KeepAliveWrapper extends StatefulWidget {
  final bool keepAlive;

  final Widget child;

  final void Function() callback;

  const _KeepAliveWrapper({
    this.keepAlive = true,
    required this.child,
    required this.callback,
  });

  @override
  _KeepAliveWrapperState createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<_KeepAliveWrapper> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    widget.callback.call();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.child;
  }

  @override
  void didUpdateWidget(covariant _KeepAliveWrapper oldWidget) {
    if (oldWidget.keepAlive != widget.keepAlive) {
      /// keepAlive 状态需要更新，实现在 AutomaticKeepAliveClientMixin 中
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;
}
